package com.csnf.jtz.servlet;

import com.csnf.jtz.entity.Student;
import com.csnf.jtz.service.StudentService;
import com.csnf.jtz.service.impl.StudentServicelmpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.time.LocalDate;

@WebServlet(name = "StudentServlet", value = {"/StudentServlet","/getAllStudent"})
public class StudentServlet extends HttpServlet {
    StudentService studentService  = new StudentServicelmpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        getstu(req, resp);
    }

    private void getstu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("students",studentService.getAll());
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //获取页面填写信息
        String name = req.getParameter("name");
        String gender = req.getParameter("gender");
        String sBirthday = req.getParameter("birthday");
        LocalDate birthday = LocalDate.parse(sBirthday);
        String clazz = req.getParameter("clazz");
        String state = req.getParameter("state");
        //通过信息创建学生对象
        Student student = new Student(null,name,gender,birthday,clazz,state);

        try {
             studentService.addStudent(student);  //调用保存方法
        } catch (Exception e) {
            e.printStackTrace();
        }
        getstu(req, resp);
    }



}